package emulator.shell.GUI.menu;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

import emulator.shell.GUI.viewmodel.RegisterTableModel;

@SuppressWarnings("serial")
public class ViaRegistersDialog extends JDialog
{
	private JTable registerTable;
	private RegisterTableModel registerTableModel;
	private boolean resultValid = false;

	public ViaRegistersDialog(JFrame parent, String title, String subTitle)
	{
		super(parent, title, true);
		buildContents(subTitle);
		pack();
		setLocationRelativeTo(null); 
	}

	private void buildContents(String subTitle)
	{
		setLayout(new BorderLayout());
		
		add(new JLabel(subTitle), BorderLayout.PAGE_START);
		
        registerTable = new JTable();
        registerTableModel = new RegisterTableModel();
		registerTable.setModel(registerTableModel);
        for (int i = 0; i < registerTableModel.getColumnCount(); i++)
        {
        	TableColumn column = registerTable.getColumnModel().getColumn(i);
            column.setPreferredWidth(registerTableModel.getColumnWidth(i));
        }
        registerTable.setFillsViewportHeight(true);
        add(registerTable, BorderLayout.CENTER);
        
        JButton buttonOk = new JButton("OK");
        buttonOk.addActionListener(new OnOk());
        add(buttonOk, BorderLayout.PAGE_END);
	}

	public void setRegisterValue(int registerIndex, int value)
	{
		registerTableModel.setRegisterValue(registerIndex, value);
	}
	
	public int getRegisterValue(int registerIndex)
	{
		return registerTableModel.getRegisterValue(registerIndex);
	}
	
	public boolean isResultValid()
	{
		return resultValid;
	}

	private class OnOk implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent e)
		{
			if (registerTable.isEditing())
				registerTable.getCellEditor().stopCellEditing();
			resultValid  = true;
			ViaRegistersDialog.this.setVisible(false);
		}
	}
}
